/*
 * toast.js
 * Toast组件，用于在页面上显示消息
 * 参数说明：
 * @params messageOrOptions<String|Object>: 消息内容，或者对象形式传参
 * @params time<Number>: 消息显示时间，单位秒，默认3秒,time与callback可互换位置
 * @params cb<function>: 消息消失后的回调函数,无参数
 * @params type<String>: 消息类型，可选值：error、success、info、warning、black，默认black
 * @params position<String>: 消息位置，枚举值：left-top、left-middle、left-bottom、center-top、center-middle、center-bottom、right-top、right-middle、right-bottom
 * @return 无返回值
 * 使用说明：
 * @example showToast('一条默认3秒的消息')
 * @example showToast({msg: '这是一条信息', type: 'info'},cb:()=>{})
 */
(function () {
  let criticalTime = 1.8//动画类型的临界点,单位:秒,根据动画总时长的不同,小于1.8则渐隐,否则缩小一点后渐隐
  // 用于生成唯一ID的计数器，模块私有
  let toastCounter = 0;
  const ToastType = ['error', 'success', 'info', 'warning']
  // 确保toast容器存在
  function getToastWrapper() {
    let container = document.getElementById('wsj-toast-container');
    if (!container) {
      container = document.createElement('div');
      container.id = 'wsj-toast-container';
      document.body.appendChild(container);
    }
    return container;
  }
  function gettoastItemPositionType(position) {
    let container = document.getElementById(`wsjtoast-${position}`);
    if (!container) {
      container = document.createElement('div');
      container.id = `wsjtoast-${position}`;
      container.className = `wsjtoast-item`
    }
    return container;
  }

  // 将showToast函数暴露到全局作用域
  window.showToast = function (messageOrOptions, time = 3, cb = () => { }, type = 'black', position = 'center-middle') {
    // 支持对象形式传参
    let msg = ''
    // 检查是否为对象形式传参
    if (typeof messageOrOptions === 'object' && messageOrOptions !== null) {
      msg = messageOrOptions.msg || '';
      time = messageOrOptions.time || time
      cb = messageOrOptions.cb || cb
      type = ToastType.includes(messageOrOptions.type) ? messageOrOptions.type : type;
      position = messageOrOptions.position || position;
    } else {
      // 非对象调用方式
      msg = messageOrOptions;
      for (let i = 1; i < arguments.length; i++) {
        if (typeof arguments[i] === 'function') {
          cb = arguments[i]
        }
        if (typeof arguments[i] === 'number') {
          time = arguments[i]

        }
        if (typeof arguments[i] === 'string') {
          if (arguments[i].includes('-')) {
            position = arguments[i]
          } else {
            type = ToastType.includes(arguments[i]) ? arguments[i] : type;
          }
        }
      }

      //二次验证,为了乱序的实参能归位
      if (typeof cb !== 'function') { cb = () => { } }
      if (typeof time !== 'number') { time = 3 }
      if (!position.includes('-')) { position = 'center-middle' }
      if (!ToastType.includes(type)) { type = 'black' }
    }
    const toastItemPositionType = gettoastItemPositionType(position)
    const [horizontal, vertical] = position.split('-');
    toastItemPositionType.classList.add(`wsjtoast-${horizontal}`);
    toastItemPositionType.classList.add(`wsjtoast-${vertical}`);
    const toastWrapper = getToastWrapper();

    const toast = document.createElement('div');
    const toastMessage = document.createElement('div');


    toast.id = `wsjtoast-${toastCounter}`;
    toast.className = `wsjtoast-base wsjtoast-${type}`;
    toastMessage.innerHTML = msg;

    // 添加到容器
    toast.appendChild(toastMessage);
    toastItemPositionType.appendChild(toast);
    toastWrapper.appendChild(toastItemPositionType);
    toastCounter++
    var animation
    if (time >= criticalTime) {
      animation = toast.animate([
        {
          offset: 0,
          opacity: 1,
          transform: 'scale(1)'
        },
        {
          offset: 0.1,
          opacity: 1,
          transform: 'scale(0.93)'
        },
        {
          offset: 0.8,
          opacity: 1,
          transform: 'scale(0.93) translateY(0)'
        },
        {
          offset: 1,
          opacity: 0,
          transform: 'scale(0.93) translateY(10px)'
        }
      ], {
        duration: 800,// time*1000
        easing: 'linear',
        fill: 'both',
        delay: time * 1000 - 800
      })
    } else {
      animation = toast.animate(
        [
          {
            offset: 0,
            opacity: 1
          },
          {
            offset: 0.85,
            opacity: 1,
            transform: 'translateY(0)'
          },
          {
            offset: 1,
            opacity: 0.5,
            transform: 'translateY(10px)'
          }
        ], {
        easing: 'linear',
        duration: time * 1000
      })
    }

    // 当动画完成时移除元素
    animation.finished.then(() => {
      var toastParentEl = toast.parentElement
      toastParentEl.removeChild(toast);
      if (toastParentEl.children.length === 0) {
        toastParentEl.parentElement.removeChild(toastParentEl);
      }
      // 如果容器为空，移除容器
      if (toastWrapper.children.length === 0) {
        document.body.removeChild(toastWrapper);
      }
      cb()
    });
  };
})();